package com.my.screens;

import java.io.IOException;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Array;
import com.my.drinkinggame.Main;
import com.my.drinkinggame.Renderer;
import com.my.drinkinggame.StaticFonts;
import com.my.drinkinggame.StaticSprites;
import com.my.simulation.Card;
import com.my.simulation.Card.CardType;

public class CreateCard extends Screen {
	Main main;
	public OrthographicCamera cam;
	Vector3 translationVector;
	public Sprite headerBut;
	public Sprite contentBut;
	public Sprite activeSave;
	public Sprite activeCancel;
	public Sprite activeDelete;
	public boolean showHeader, showContent, resetButtons, modifying;
	public float xPos;
	public float yPos;
	public Sprite bg;
	public String headerString;
	public String contentString;
	public String originalHeader;
	public Array<Character> headerText;
	public Array<Character> contentText;
	public CreateCard(Main m) {
		cam = new OrthographicCamera();
		translationVector = new Vector3();
		main = m;
		headerBut = StaticSprites.headerBut;
		contentBut = StaticSprites.contentBut;
		activeSave = StaticSprites.saveBut;
		activeCancel = StaticSprites.cancelBut;
		activeDelete = StaticSprites.deleteBut;
		showHeader = true;
		showContent = true;
		resetButtons = false;
		modifying = false;
		headerString = "";
		contentString = "";
		headerText = new Array<Character>();
		contentText = new Array<Character>();
		xPos = 0;
		yPos = 0;
	}

	public void resetAll(){
		showHeader = true;
		showContent = true;
		modifying = false;
		headerString = "";
		contentString = "";
		headerText.clear();
		contentText.clear();
	}
	
	public void setHC(String cardData){
		String[] temp = cardData.split("#");
		for(int b = 0; b < temp.length; b++){
			if(b == 0){
				headerString = temp[0].substring(0, temp[0].length()-1);
				for(int i = 0; i < headerString.length(); i++){
					headerText.add(headerString.charAt(i));
				}
			}
			if(b == 1){
				contentString = temp[1];
				for(int j = 0; j < contentString.length(); j++){
					contentText.add(contentString.charAt(j));
				}
			}		
		}
		originalHeader = headerString;
		modifying = true;
	}

	public void enter() {
		Gdx.input.setCatchBackKey(true);
		Gdx.input.setInputProcessor(this);
	}

	@Override
	public boolean keyDown(int arg0) {
		if (Input.Keys.BACK == arg0) {
			resetAll();
			main.setScreen(Main.SCREEN_MAINMENU);
		}
		return false;
	}

	@Override
	public boolean keyTyped(char finalChar) {
		if (!showHeader) {
			if (finalChar == 8){ // backspace
				if (headerText.size>0) 
					headerText.removeIndex(headerText.size-1);
				StringBuilder fName = new StringBuilder();
				for (int i = 0; i < headerText.size; i++) {
					fName.append(headerText.get(i));
				}
				headerString = fName.toString();
			} 
			else if (finalChar == 13 || finalChar == 10) { // enter
				StringBuilder fName = new StringBuilder();
				for (int i = 0; i < headerText.size; i++) {
					fName.append(headerText.get(i));
				}
				if (fName.toString().length() > 0) {
					showHeader = true;
					Gdx.input.setOnscreenKeyboardVisible(false);
				}
			}
			else if ("0123456789abcdefghijklmnopqrstuvwxyz.,!?' ".contains(Character.toString(finalChar).toLowerCase())){
				headerText.add(finalChar);
				StringBuilder fName = new StringBuilder();
				for (int i = 0; i < headerText.size; i++) {
					fName.append(headerText.get(i));
				}
				headerString = fName.toString();
			}
		}
		if (!showContent) {
			if (finalChar == 8){ // backspace
				if (contentText.size>0) 
					contentText.removeIndex(contentText.size-1);
				StringBuilder fName = new StringBuilder();
				for (int i = 0; i < contentText.size; i++) {
					fName.append(contentText.get(i));
				}
				contentString = fName.toString();
			} 
			else if (finalChar == 13 || finalChar == 10) { // enter
				StringBuilder fName = new StringBuilder();
				for (int i = 0; i < contentText.size; i++) {
					fName.append(contentText.get(i));
				}
				if (fName.toString().length() > 0) {
					showContent = true;
					Gdx.input.setOnscreenKeyboardVisible(false);
				}
			}
			else if ("0123456789abcdefghijklmnopqrstuvwxyz.,!?' ".contains(Character.toString(finalChar).toLowerCase())){
				contentText.add(finalChar);
				StringBuilder fName = new StringBuilder();
				for (int i = 0; i < contentText.size; i++) {
					fName.append(contentText.get(i));
				}
				contentString = fName.toString();
			}
		}
		return false;
	}

	@Override
	public boolean keyUp(int arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean scrolled(int arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean touchDown(int x, int y, int arg2, int arg3) {
		translationVector.set(x,y,0);
		cam.unproject(translationVector);
		xPos = translationVector.x;
		yPos = translationVector.y;
		resetButtons = false;
		if(!showHeader || !showContent){
			showHeader = true;
			showContent = true;
			Gdx.input.setOnscreenKeyboardVisible(false);
		}
		return false;
	}

	@Override
	public boolean touchDragged(int x, int y, int arg2) {
		translationVector.set(x,y,0);
		cam.unproject(translationVector);
		xPos = translationVector.x;
		yPos = translationVector.y;
		return false;
	}

	public boolean touchMoved(int x, int y) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean touchUp(int x, int y, int arg2, int arg3) {
		translationVector.set(x,y,0);
		cam.unproject(translationVector);
		if(headerBut.getBoundingRectangle().contains(translationVector.x, translationVector.y)){
			showHeader = false;
			Gdx.input.setOnscreenKeyboardVisible(true);
		}
		if(contentBut.getBoundingRectangle().contains(translationVector.x, translationVector.y)){
			showContent = false;
			Gdx.input.setOnscreenKeyboardVisible(true);
		}
		if(activeSave.getBoundingRectangle().contains(translationVector.x, translationVector.y)
				&& (headerString.length() > 0 && contentString.length() > 0)){
			FileHandle f = Gdx.files.external("HHObeergame/"+headerString+".HHO");
			if (f.exists()) {
				f.delete(); //overwrite
			}
			try {
				Gdx.app.log("key", "tried " + f.file().getAbsolutePath());
				f.file().createNewFile();
				f.writeString(headerString + "\n#\n" + contentString, false);
				Gdx.app.log("key", "all good");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Gdx.app.log("key", "failed");
				e.printStackTrace();
			}
			Card newCard = new Card(CardType.REGULAR);
			newCard.setHeader(headerString);
			newCard.setText(contentString);
			resetAll();
			((MyDrinkingGame) main.getState(Main.SCREEN_GAME)).sim.cardList.add(newCard);
			main.setScreen(Main.SCREEN_MAINMENU);

		}
		if(activeCancel.getBoundingRectangle().contains(translationVector.x, translationVector.y)){
			resetAll();
			main.setScreen(Main.SCREEN_MAINMENU);
		}
		if(activeDelete.getBoundingRectangle().contains(translationVector.x, translationVector.y)){
			if(modifying){
				FileHandle f = Gdx.files.external("HHObeergame/"+originalHeader+".HHO");
				if (f.exists()) {
					f.delete(); //delete
				}
				resetAll();
				main.setScreen(Main.SCREEN_ADDEDCARDS);
			}
		}
		
		resetButtons = true;
		return false;
	}

	public void resetButs(){
		activeSave = StaticSprites.saveBut;
		activeCancel = StaticSprites.cancelBut;
		activeDelete = StaticSprites.deleteBut;
	}

	public void updateSaveBut(){
		if(activeSave.getBoundingRectangle().contains(xPos, yPos)){
			activeSave = StaticSprites.saveButSel;
		}
		else{
			activeSave = StaticSprites.saveBut;
		}
	}

	public void updateCancelBut(){
		if(activeCancel.getBoundingRectangle().contains(xPos, yPos)){
			activeCancel = StaticSprites.cancelButSel;
		}
		else{
			activeCancel = StaticSprites.cancelBut;
		}
	}
	
	public void updateDeleteBut(){
		if(activeDelete.getBoundingRectangle().contains(xPos, yPos)){
			activeDelete = StaticSprites.deleteButSel;
		}
		else{
			activeDelete = StaticSprites.deleteBut;
		}
	}

	@Override
	public void update() {
		updateSaveBut();
		updateCancelBut();
		updateDeleteBut();
		if(resetButtons){
			resetButs();
		}
	}


	@Override
	public void render() {
		Renderer.getInstance().renderCreateCard(this);
	}

	public void renderCreateCard(SpriteBatch sb) {
		StaticSprites.cardBGSprite.draw(sb);
		StaticFonts.comic_48.setScale(2f, 2f);
		headerBut.setPosition(StaticSprites.cardBGSprite.getX()+
				StaticSprites.cardBGSprite.getWidth()/2-StaticSprites.headerBut.getWidth()/2,
				cam.position.y+Gdx.graphics.getHeight()/2.6f);
		if(showHeader){
			headerBut.draw(sb);
		}
		if(!showHeader || headerString.length() > 0){
			StaticFonts.comic_48.draw(sb, headerString, cam.position.x-StaticFonts.comic_48.getBounds(headerString).width/2,
					cam.position.y+Gdx.graphics.getHeight()/2.6f);
		}
		contentBut.setPosition(StaticSprites.cardBGSprite.getX()+
				StaticSprites.cardBGSprite.getWidth()/2-StaticSprites.contentBut.getWidth()/2,
				cam.position.y+Gdx.graphics.getHeight()/5f);
		if(showContent){
			contentBut.draw(sb);
		}
		//the splitting is done on words. There is no stopping one word to run across the screen without being cut.
		if(!showContent || contentString.length() > 0){
			if(StaticFonts.comic_48.getBounds(contentString).width > StaticSprites.cardBGSprite.getWidth()/2f){
				String[] listStrings = contentString.split(" ");
				int index = 0;
				int row = 1;
				String temp = "";
				while(index < listStrings.length){
					temp += (listStrings[index] + " ");
					if(StaticFonts.comic_48.getBounds(temp).width > StaticSprites.cardBGSprite.getWidth()/2f){
						StaticFonts.comic_48.draw(sb, temp, StaticSprites.cardBGSprite.getX()+
								StaticSprites.cardBGSprite.getWidth()/2-StaticFonts.comic_48.getBounds(temp).width/2, 
								StaticSprites.cardBGSprite.getY()+StaticSprites.cardBGSprite.getHeight()/1.35f-
								StaticFonts.comic_48.getBounds(temp).height*row);
						row++;			
						temp = "";
					}
					index++;
				}
				StaticFonts.comic_48.draw(sb, temp, StaticSprites.cardBGSprite.getX()+
						StaticSprites.cardBGSprite.getWidth()/2-StaticFonts.comic_48.getBounds(temp).width/2, 
						StaticSprites.cardBGSprite.getY()+StaticSprites.cardBGSprite.getHeight()/1.35f-
						StaticFonts.comic_48.getBounds(temp).height*row);

			}
			else{
				StaticFonts.comic_48.draw(sb, contentString, StaticSprites.cardBGSprite.getX()+
						StaticSprites.cardBGSprite.getWidth()/2-
						StaticFonts.comic_48.getBounds(contentString).width/2, 
						StaticSprites.cardBGSprite.getY()+StaticSprites.cardBGSprite.getHeight()/1.35f-
						StaticFonts.comic_48.getBounds("").height);
			}
		}
		if(modifying){
			activeDelete.setPosition(cam.position.x-StaticSprites.deleteBut.getWidth()/2-StaticSprites.deleteBut.getWidth(), 
					cam.position.y-Gdx.graphics.getHeight()/2.3f);
			activeDelete.draw(sb);
		}
		if((headerString.length() > 0 && contentString.length() > 0) && (showContent && showHeader)){
			activeSave.setPosition(cam.position.x-StaticSprites.saveBut.getWidth()/2, 
					cam.position.y-Gdx.graphics.getHeight()/2.3f);
			activeSave.draw(sb);
		}
		activeCancel.setPosition(cam.position.x-StaticSprites.saveBut.getWidth()/2+StaticSprites.cancelBut.getWidth(), 
				cam.position.y-Gdx.graphics.getHeight()/2.3f);
		activeCancel.draw(sb);
		
	}

	public boolean mouseMoved(int screenX, int screenY) {
		// TODO Auto-generated method stub
		return false;
	}
}
